<template>
  <div id="permission">
    <div class="menu-list">
      <el-tree
        ref="eltree"
        :data="treeData"
        :props="defaultProps"
        node-key="id"
        highlight-current
        :default-expanded-keys="[]"
        :expand-on-click-node="true"
        @node-click	="nodeClick"
        >
        <span class="el-tree-node__label" slot-scope="{ node, data }" @mouseover="hoverNodeId=data.id" @mouseout="hoverNodeId=''">
          <span class="label el-icon-menu"  v-if="data.type=='0'">{{ node.label }}</span>
          <span class="label el-icon-s-grid" v-if="data.type=='1'">{{ node.label }}</span>
          <span class="label el-icon-thumb" v-if="data.type=='2'">{{ node.label }}</span>
          <span class="btn-bar" v-show="hoverNodeId==data.id">
            <i class="el-icon-menu" title="新增根级菜单" @click.stop="appendNode(data,'root')" v-if="data.type=='0'"></i>
            <i class="el-icon-s-grid" title="新增子菜单" @click.stop="appendNode(data,'menu')" v-if="data.type!='2'"></i>
            <i class="el-icon-thumb" title="新增按钮" @click.stop="appendNode(data,'button')"></i>
            <i class="el-icon-delete" title="删除" @click.stop="deleteNode(node,data)"></i>
          </span>
        </span>
      </el-tree>
    </div>
    <div class="view-box">
      <el-form class="warpper menu-view"  ref="menuForm" :model="menuForm" label-width="80px" :rules='validateRule1'  v-show="activeNode.type!='2'">
          <el-form-item label="菜单名称" prop='name' >
              <el-input maxlength="8" v-model="menuForm.name"  :readonly="mode=='view'"></el-input>
          </el-form-item>
          <el-form-item label="菜单路由" prop='url' v-show="menuForm.parentId!='-1'">
              <el-input v-model="menuForm.url"  :readonly="mode=='view'"></el-input>
          </el-form-item>
          <el-form-item label="菜单图标" prop='icon' >
              <el-input v-model="menuForm.icon"  :suffix-icon="menuForm.icon" :readonly="mode=='view'" ></el-input>
          </el-form-item>
          <el-form-item label="权限标识" prop='code' >
              <el-input maxlength="64" v-model="menuForm.code"  :readonly="mode=='view'">
				  <span slot="suffix" class="el-input__icon el-icon-refresh-right" @click="refreshPmsCode" :style="{'pointer-events': mode=='view' ? 'none' :'auto'}"></span>
			  </el-input>
          </el-form-item>
          <el-form-item class="btn-bar">
              <el-button type=""  size="mini" v-show="mode=='edit' && activeNode.id!='new'" @click="onCancel">取消</el-button>
              <el-button type="warning" size="mini" v-show="mode=='view'"  @click="onEdit">编辑</el-button>
              <el-button type="primary" size="mini" v-show="mode=='edit'"  @click="onSave('menuForm')" :loading="btnLoading">保存</el-button>
          </el-form-item>
      </el-form>
      <el-form class="warpper button-view"  ref="buttonForm" :model="buttonForm" label-width="80px" :rules='validateRule2'  v-show="activeNode.type=='2'">
          <el-form-item label="按钮名称" prop='name' >
              <el-input maxlength="8" v-model="buttonForm.name" :readonly="mode=='view'"></el-input>
          </el-form-item>
          <el-form-item label="上级菜单" prop='parentMenu'v-show="false">
              <el-input v-model="buttonForm.parentMenu" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="权限标识" prop='code' >
              <el-input maxlength="20" v-model="buttonForm.code" :readonly="mode=='view'">
				  <span slot="suffix" class="el-input__icon el-icon-refresh-right" @click="refreshPmsCode" :style="{'pointer-events': mode=='view' ? 'none' :'auto'}"></span>
			  </el-input>
          </el-form-item>
          <el-form-item class="btn-bar">
              <el-button type="" size="mini"  v-show="mode=='edit' && activeNode.id!='new'" @click="onCancel">取消</el-button>
              <el-button type="warning" size="mini" v-show="mode=='view'"  @click="onEdit">编辑</el-button>
              <el-button type="primary" size="mini" v-show="mode=='edit'"  @click="onSave('buttonForm')"  :loading="btnLoading">保存</el-button>
          </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
  export default{
    data(){
      return{
        mode:"view",//view||edit
        defaultProps:{
          children: 'children',
          label: 'name'
        },
        treeData:[
          {
			  id:"new",
            name:"新菜单",
            type:0,
            icon:"el-icon-menu",
            parentId:"-1",
			code:"9527",
          }
        ],
        activeNode:{
          type:'menu'
        },
        expandId:"",
        hoverNodeId:"",
        menuForm:{
			id:"new",
          name:"新菜单",
          url:"",
          icon:"el-icon-menu",
          code:"9527",
          type:'0',//0-无路由菜单，1-有路由菜单，2-按钮
        },
        buttonForm:{
			id:"new",
          name:"",
          parentMenu:"",
          code:"9527",
          type:"2"
        },
        validateRule1:{
          name:[
            {required: true, message: '请输入菜单名称', trigger: 'blur'},
            {max: 8, message: '不要超过8个字符!', trigger: 'change'},
          ],
		  code:[
		    {required: true, message: '请输入菜单权限标识', trigger: 'blur'},
		    {max: 20, message: '不要超过20个字符!', trigger: 'change'}
		  ]
        },
        validateRule2:{
          name:[
            {required: true, message: '请输入按钮名称', trigger: 'blur'},
            {max: 8, message: '不要超过8个字符!', trigger: 'change'},
          ],
          code:[
            {required: true, message: '请输入按钮权限标识', trigger: 'blur'},
            {max: 20, message: '不要超过20个字符!', trigger: 'change'}
          ]
        },
		
		btnLoading:false
      }
    },
	watch:{
		'menuForm.code'(vv){
			//console.log(vv)
		}
	},
    methods:{
      getTreeDada(){
        var _this=this;
        this.$http.getPmsTree()
        .then(res=>{
            this.treeData = res.data.data ||[];
            //默认高亮并展开第一个菜单
            if(this.treeData.length==0){
              this.mode='edit';
              this.activeNode=Object.assign({},this.menuForm);
              this.$refs.eltree.setCurrentKey(this.activeNode.id);
            }else{
              if(!_this.expandId){
                this.activeNode=this.treeData[0];
                this.menuForm=Object.assign({},this.activeNode);
              }else{
                this.activeNode=this.$refs.eltree.getNode(_this.expandId).data;
                this.$nextTick(()=>{
                  setTimeout(()=>{
                    this.$refs.eltree.setCurrentKey(_this.expandId || this.treeData[0].id);
                    this.$refs.eltree.store.nodesMap[_this.expandId].expanded = true;
					console.log(111,this.activeNode.parentId)
					if(this.activeNode.parentId && this.activeNode.parentId !=-1){
						this.$refs.eltree.setCurrentKey(this.activeNode.parentId );
						this.$refs.eltree.store.nodesMap[this.activeNode.parentId].expanded = true;
					}
                  },200)
                })
              }
            }
        }).catch(err=>{
            console.log(err)
        })
      },

      nodeClick(nodeData,node){
        //展开节点，显示节点信息
        this.activeNode=nodeData;
        if(this.activeNode.type=='0' || this.activeNode.type=='1'){
          this.menuForm=Object.assign({},this.activeNode) ;
        }else{
          this.buttonForm=Object.assign({},this.activeNode);
        }
		
		if(nodeData.type!='2'){
			this.expandId=nodeData.id
		}

      },

      appendNode(nodeData,type){
        var bool=this.$refs.eltree.getNode("new");
		var newNode=null;
		if(nodeData.id=='new'){
          this.$message.warning("请先编辑并保存当前节点!")
          return
        }else if(bool){
         //this.$message.warning("请先编辑并保存刚才新建的节点!")
         //return
        }
        if(this.activeNode.id=='new'){
          this.$message.warning("请先编辑并保存刚才新建的节点!")
          return
        }

        this.mode='edit';
		
        if(type!='root'){
           //展开点击的节点
          this.$refs.eltree.store.nodesMap[nodeData.id].expanded = true;
        }
        if(type=='root'){
          this.menuForm={
            id:"new",
            parentId:"-1",
            name:"新菜单",
            url:"",
            icon:"el-icon-menu",
            type:"0",
            code:this.createPmsId("-1")
          }
		  newNode=this.menuForm
          this.activeNode=Object.assign({},this.menuForm);

        }else if(type=='menu'){
          this.menuForm={
            id:"new",
            parentId:nodeData.id,
            name:"新菜单",
            url:"",
            icon:"el-icon-s-grid",
            type:"1",
            code:this.createPmsId(nodeData.id)
          }
		  newNode=this.menuForm
          this.activeNode=Object.assign({},this.menuForm);
          this.expandId=nodeData.id
		  
        }else{
          this.buttonForm={
            id:"new",
            parentId:nodeData.id,
            name:"新按钮",
            parentMenu:nodeData.name,
            type:"2",
            code:this.createPmsId(nodeData.id)
          }
		  newNode=this.buttonForm
          this.activeNode=Object.assign({},this.buttonForm);
          this.expandId=nodeData.id
        }

        //let newNode = this.activeNode;
        if(type=='root'){
          this.$refs.eltree.insertAfter(newNode,nodeData.id)
          //this.treeData.push(newNode)
        }else{
          if (!nodeData.children) {
            this.$set(nodeData, 'children', []);
          }
          nodeData.children.push(newNode);
        }


         //高亮当前节点
        this.$nextTick(()=>{
          setTimeout(()=>{
             this.$refs.eltree.setCurrentKey("new");
          },100)
        })
      },

      deleteNode(nodeData){
        if(nodeData.key=='new'){
          this.$refs.eltree.remove(nodeData.key)
          this.$refs.eltree.setCurrentKey(this.expandId || this.treeData[0].id);
          this.mode='view';
          if(nodeData.data.parentId=='-1'){
            this.activeNode=this.treeData[0];
            this.menuForm=Object.assign({},this.activeNode);
            this.expandId="";
          }else{
            let parenNode=this.$refs.eltree.getNode(nodeData.data.parentId)
            this.activeNode=parenNode.data;
            this.menuForm=Object.assign({},this.activeNode);
            this.expandId=this.activeNode.id;
          }

          return
        }
        this.$confirm('请确认是否删除?', '警告', {
           confirmButtonText: '确定',
           cancelButtonText: '取消',
           type: 'warning'
         }).then(() => {
           this.$http.deletePmsTree({id:nodeData.key})
           .then(res=>{
             this.$refs.eltree.remove(nodeData.key)
             this.$message.success('删除成功!');
             this.mode='view';
             this.$refs.eltree.setCurrentKey(this.expandId || this.treeData[0].id);
           }).catch((err)=>{
             console.log(err)
           })
         })
      },

      onEdit(){
        this.mode='edit';
      },
      onCancel(){
        this.mode='view';
        if(this.activeNode.type=='0' || this.activeNode.type=='1'){
          this.menuForm=Object.assign({},this.activeNode) ;
        }else{
          this.buttonForm=Object.assign({},this.activeNode);
        }
      },

      onSave(form){
        var isValidate=false;
        var submitData={}
		var flag={bool:false};
        this.$refs[form].validate((bool)=>{
            if(bool){
              isValidate=true
            }
        })
		
		this.travers(this.treeData,this[form],flag)//验证code是否唯一
        if(!isValidate){
			return
		}else if(flag.bool){
			this.$message.warning("code不可重复!")
			return
		}

        if(form=='menuForm'){
          submitData=Object.assign({},this.menuForm) ;
        }else{
          submitData=Object.assign({},this.buttonForm);
        }

        if(this.activeNode.id=='new'){
          delete submitData.id;
        }
		this.btnLoading=true
        this.$http.editPmsTree(submitData)
        .then(res=>{
          this.$message.success("保存成功!")
          this.mode='view';
          this.getTreeDada()
		  this.btnLoading=false
        }).catch(err=>{
			this.btnLoading=false
            console.log(err)
        })

      },

      //随机生成4位数权限码
      createPmsId(pid,length){
        var charArr=[];
        var length=length || 4;
        var code="";
        if(pid!='-1' && pid!='new' && pid!=undefined){
          charArr=pid.split("");
        }else{
          charArr=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        }
        for(var i=1;i<=length;i++){
          let charIndex = Math.floor(Math.random() * charArr.length);
          code  = code + charArr[charIndex];
        }

        return code;
      },
	  
	  refreshPmsCode(){
		  if(this.activeNode.type=="0"){
			  this.menuForm.code=this.createPmsId()
		  }else if(this.activeNode.type=="1"){
			  this.menuForm.code=this.createPmsId()
		  }else{
			  this.buttonForm.code=this.createPmsId()
		  }
	  },
	  
	  //对象遍历查询-查询对象树obj是否存在code属性值等于newCode
	    travers(obj,newNode,flag){
	      if(!obj || !obj instanceof Object){
	        return
	      }
	      if(Object.prototype.toString.call(obj)==="[object Array]"){
	          if(obj.length===0){
	              return
	          }
	          obj.forEach((item)=>{
	              this.travers(item,newNode,flag)
	          })
	      }else if(Object.prototype.toString.call(obj)==="[object Object]"){
	          if(obj.id !=newNode.id && obj.code==newNode.code){
				  //flag.push(obj)
	              flag.bool=true //符合条件
				  return //符合条件可以不再循环
	          }
	          if(obj.children && obj.children instanceof Array){
	              obj.children.forEach((item)=>{
	                  this.travers(item,newNode,flag)
	              })
	              
				}else{
					return
				}
	      }
	  }


    },

    created() {
      this.getTreeDada()
    }
  }
</script>
<style scoped="scoped" lang="scss">
#permission{
  height: 100%;
  display: flex;
  flex-direction: row;
}


.menu-list{
  width:400px;
  overflow: auto;
  margin:10px;
  padding-right:10px;
  border-right: 1px solid #eee;
}

.view-box{
  flex:1;
  margin:10px;
}

.warpper{
  max-width: 700px;
}


/deep/ .el-tree{
  .el-tree-node__content{
    cursor: default;
  }
  .el-tree-node__label{
    height: 100%;
    flex:1;
    display: flex;
    justify-content: space-between;
    align-items: center;
    overflow: hidden;
    .label{
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-right: 20px;
      &.el-icon-menu:before{
        color:#7cb1ff;
        margin-right: 7px;
      }
      &.el-icon-s-grid:before{
        color:#94fbda;
        margin-right: 7px;
      }
      &.el-icon-thumb:before{
        color:#f7b012;
        margin-right: 7px;
      }
    }
    .btn-bar{
      color: #69a9e0;
      i{
        margin-right: 10px;
        cursor: pointer;
      }

    }
  }
}

/deep/ .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
    background-color:rgba(73, 142, 214, 0.29);
}

.btn-bar .el-button{
  margin-left: 0px;
  margin-right: 20px;
}

/deep/ .el-input{
  .el-input__suffix .el-input__icon{
    font-size: 22px;
    color:#ccc;
  }
  .el-input__inner[readonly]{
    //border-color:rgba(255,255,255,0.1);
	border-color:#f6f6f6;
    cursor: default;
  }
}
</style>
